package org.chen.wordwave.act;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastParams;
import com.hjq.toast.Toaster;
import com.hjq.toast.style.CustomToastStyle;
import com.yalantis.ucrop.UCrop;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.base.BaseActivity;
import org.chen.wordwave.bean.UpdateUserInfo;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.bean.UserRegisterRequest;
import org.chen.wordwave.init.WordInit;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UserProfile extends BaseActivity {
    private static final int PICK_IMAGE_REQUEST = 1;
    private static final String PREFS_NAME = "UserPrefs";
    private static final String KEY_AVATAR_PATH = "avatarPath";
    private ImageView ivProfilePicture;
    private EditText etUsername;
    private EditText etEmail;
    private EditText etCity;
    private Spinner spinnerGender;
    private Button btnUploadPicture;
    private Button btnSave;
    private ToastParams toastParams = new ToastParams();
    private UserInfo currentUser;
    private ToastParams params = new ToastParams();
    private boolean isUsernameAvailable = true;
    private TextView tv_userName, tv_userEmail, tv_registerTime;

    @Override
    public Integer getLayoutResId() {
        return R.layout.user_profile;
    }

    @Override
    public void init() {
        ivProfilePicture = findViewById(R.id.iv_profile_picture);
        etUsername = findViewById(R.id.et_username);
        etEmail = findViewById(R.id.et_email);
        etEmail.setEnabled(false);
        etCity = findViewById(R.id.et_city);
        spinnerGender = findViewById(R.id.spinner_gender);
        btnUploadPicture = findViewById(R.id.btn_upload_picture);
        btnSave = findViewById(R.id.btn_save);
        tv_userName = findViewById(R.id.tv_userName);
        tv_userEmail = findViewById(R.id.tv_userEmail);
        tv_registerTime = findViewById(R.id.tv_registerTime);

        loadUserData();

        btnUploadPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openPhotoPicker();
            }
        });

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUsernameAvailable) {
                    saveUserData();
                } else {
                    params.text = getString(R.string.email_or_account_exits);
                    params.style = new CustomToastStyle(R.layout.error);
                    Toaster.show(params);
                }
            }
        });

        etUsername.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    checkUserNameExists(etUsername.getText().toString().trim());
                }
            }
        });

        loadAvatar();
    }

    private void openPhotoPicker() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // 使用新的 Photo Picker API
            Intent intent = new Intent(MediaStore.ACTION_PICK_IMAGES);
            intent.setType("image/*");
            startActivityForResult(intent, PICK_IMAGE_REQUEST);
        } else {
            // 对于较老的 Android 版本，使用传统的图片选择器
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(intent, PICK_IMAGE_REQUEST);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == PICK_IMAGE_REQUEST && data != null && data.getData() != null) {
                Uri sourceUri = data.getData();
                Uri destinationUri = Uri.fromFile(new File(getCacheDir(), "cropped"));
                UCrop.of(sourceUri, destinationUri)
                        .withAspectRatio(1, 1)
                        .withMaxResultSize(500, 500)
                        .start(UserProfile.this);
            } else if (requestCode == UCrop.REQUEST_CROP) {
                handleCropResult(data);
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            handleCropError(data);
        }
    }


    private void checkUserNameExists(String userName) {
        ApiService apiService = ApiClient.getClient(this).create(ApiService.class);
        // 发送网络请求检查用户名是否存在
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setAccount(userName);
        userRegisterRequest.setId(currentUser.getId());
        apiService.registerUserInfo(userRegisterRequest).enqueue(new Callback<String>() {
            @Override
            public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                if (response.isSuccessful() && response.body() != null) {
                    String body = response.body();
                    if (body.equals("400")) {
                        etUsername.setError(null);
                        isUsernameAvailable = true;
                    } else {
                        params.text = getString(R.string.account_exits);
                        params.style = new CustomToastStyle(R.layout.error);
                        Toaster.show(params);
                        etUsername.setError(getString(R.string.account_exits));
                        isUsernameAvailable = false;
                    }
                } else {
                    showNetworkError();
                    isUsernameAvailable = false;
                }
            }

            @Override
            public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                showNetworkError();
                isUsernameAvailable = false;
            }
        });
    }

    private void showNetworkError() {
        params.text = getString(R.string.network_error);
        params.style = new CustomToastStyle(R.layout.error);
        Toaster.show(params);
    }

    private void loadUserData() {
        // Load user data from API or local storage
        ApiService apiService = ApiClient.getClient(this).create(ApiService.class);
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setEmail(WordInit.userInfo.getEmail());

        // 发起异步请求
        Call<UserInfo> call = apiService.getUserInfo(userRegisterRequest);
        call.enqueue(new Callback<UserInfo>() {
            @Override
            public void onResponse(@NonNull Call<UserInfo> call, @NonNull Response<UserInfo> response) {
                if (response.isSuccessful() && response.body() != null) {
                    currentUser = response.body();
                    updateUIWithUserInfo();
                } else {
                    toastParams.text = getString(R.string.failed_to_load_user_info);
                    toastParams.style = new CustomToastStyle(R.layout.error);
                    Toaster.show(toastParams);
                }
            }

            @Override
            public void onFailure(@NonNull Call<UserInfo> call, @NonNull Throwable t) {
                toastParams.text = getString(R.string.network_error);
                toastParams.style = new CustomToastStyle(R.layout.error);
                Toaster.show(toastParams);
            }
        });
    }

    @SuppressLint("SetTextI18n")
    private void updateUIWithUserInfo() {
        tv_userName.setText(getString(R.string.userName) + currentUser.getAccount());
        tv_userEmail.setText(getString(R.string.user) + currentUser.getEmail());
        tv_registerTime.setText(getString(R.string.register_time) + currentUser.getRegisterTime());
        etUsername.setText(currentUser.getAccount());
        etEmail.setText(currentUser.getEmail());
        etCity.setText(currentUser.getCity());
        spinnerGender.setSelection(getGenderPosition(currentUser.getGender()));
    }

    private void handleCropResult(Intent result) {
        final Uri resultUri = UCrop.getOutput(result);
        if (resultUri != null) {
            Log.e("handleCropResult", "handleCropResult");
            ivProfilePicture.setImageURI(null);
            ivProfilePicture.setImageURI(resultUri);
            saveAvatarPath(resultUri.toString());
        } else {
            // Handle error
            Toaster.show(getString(R.string.user_profile_failed));
        }
    }

    private void handleCropError(Intent result) {
        final Throwable cropError = UCrop.getError(result);
        if (cropError != null) {
            // Handle error
            Toaster.show(getString(R.string.user_profile_failed));
        } else {
            // Handle error
            Toaster.show(getString(R.string.user_profile_failed));
        }
    }

    private void saveAvatarPath(String path) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(KEY_AVATAR_PATH, path);
        editor.apply();
    }

    private void loadAvatar() {
        Log.e("loadAvatar", "loadAvatar");
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String avatarPath = prefs.getString(KEY_AVATAR_PATH, null);
        if (avatarPath != null) {
            Uri uri = Uri.parse(avatarPath);
            ivProfilePicture.setImageURI(uri);
        }
    }

    private void saveUserData() {
        currentUser.setAccount(etUsername.getText().toString());
        currentUser.setEmail(etEmail.getText().toString());
        currentUser.setCity(etCity.getText().toString());
        currentUser.setGender(spinnerGender.getSelectedItem().toString());

        ApiService apiService = ApiClient.getClient(this).create(ApiService.class);
        UpdateUserInfo updateUserInfo = new UpdateUserInfo();
        updateUserInfo.setAccount(etUsername.getText().toString().trim());
        updateUserInfo.setCity(etCity.getText().toString().trim());
        updateUserInfo.setEmail(etEmail.getText().toString().trim());
        updateUserInfo.setGender(spinnerGender.getSelectedItem().toString());
        Call<String> call = apiService.updateUserProfile(updateUserInfo);
        Log.e("currentUser", updateUserInfo.toString());
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                if (response.isSuccessful() && response.body() != null) {
                    if (response.body().equals("200")) {
                        toastParams.text = getString(R.string.user_data_saved_successfully);
                        toastParams.style = new CustomToastStyle(R.layout.success);
                        Toaster.show(toastParams);
                        loadUserData();
                    } else {
                        toastParams.text = getString(R.string.failed_to_save_user_data);
                        toastParams.style = new CustomToastStyle(R.layout.error);
                        Toaster.show(toastParams);
                    }
                } else {
                    toastParams.text = getString(R.string.network_error);
                    toastParams.style = new CustomToastStyle(R.layout.error);
                    Toaster.show(toastParams);
                }
            }

            @Override
            public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                toastParams.text = getString(R.string.network_error);
                toastParams.style = new CustomToastStyle(R.layout.error);
                Toaster.show(toastParams);
            }
        });
    }

    private int getGenderPosition(String gender) {
        String[] genders = getResources().getStringArray(R.array.gender_options);
        for (int i = 0; i < genders.length; i++) {
            if (genders[i].equalsIgnoreCase(gender)) {
                return i;
            }
        }
        return 0;
    }
}

